
<template>
    <div class="contianer">
        <div class="grid-content bg-purple">
            <div class="blog">
                <el-button type="primary" icon="el-icon-edit" circle style="float: right;" plain @click="updateBlog"
                    v-if="userType != 0"></el-button>
                <h1 v-html="tableData.title"></h1>
                <div>

                </div>
                <i class="el-icon-time" /><span>于</span><span v-html="tableData.createdTime"></span><samp>创建</samp>
                <i class="el-icon-view" /><samp v-html="tableData.clickCount"></samp>
                <i class="el-icon-thumb" /><samp v-html="tableData.likeCount"></samp>
                <i class="el-icon-star-off" /><samp>收藏&nbsp;</samp><samp v-html="tableData.collectCount"></samp>
                <div class="PSrticletag">
                    <el-tag v-for="item in tagList.slice(0, 2)" :key="item" :type="item" effect="dark">
                        {{ item }}
                    </el-tag>
                </div>
                <div class="contentDiv">
                    <p v-html="tableData.content"></p>
                </div>
            </div>


            <!-- 收藏点赞 -->
            <div class="articleFooter">
                <el-badge :value="tableData.likeCount" class="item" :type="isLike ? 'success' : 'info'" :max=999 id="badge">
                    <el-tooltip content="点赞" placement="top" effect="light">
                        <div :class="isLike ? 'like' : 'noLike'" @click="like()"></div>
                    </el-tooltip>
                </el-badge>
                <el-badge :value="tableData.collectCount" class="item" :type="isCollect ? 'success' : 'info'" :max=999>
                    <el-tooltip content="收藏" placement="top" effect="light">
                        <div :class="isCollect ? 'collect' : 'noCollect'" @click="collect()"></div>
                    </el-tooltip>
                </el-badge>
                <el-badge :value="commentNum" class="item" :type="'info'">
                    <el-tooltip content="评论" placement="top" effect="light">
                        <div class="commentbtn" @click="openComment"></div>
                    </el-tooltip>
                </el-badge>
            </div>

            <el-drawer title="文章评论" :visible.sync="drawer" :model="false" :close-on-click-modal="false" :with-header="false"
                size="500px">
                <div class="comment">
                    <div class="comment-header">
                        <div @click="handleClick">
                            <input style="display: none" ref="avatar" />
                            <el-avatar :src="avatar
                                ? avatar
                                : 'http://oos.wqun.top/img/covar/202309121941085cd86f6521ec4af390f5010590905faf.jpg'
                                " :size="30"></el-avatar>
                        </div>
                        <el-input :placeholder="placeholderText" v-model="context" class="input" type="text" resize="none"
                            size="semlla" :maxlength="contentLength" @focus="isShowSecReply(undefined)"
                            @keyup.enter.native="addComment(userId, undefined, undefined)"></el-input>

                        <el-button type="success" class="el-icon-position"
                            @click="addComment(userId, undefined, undefined)">
                            评论</el-button>
                    </div>



                    <!-- 使用列表，重建评论表 -->
                    <table class="commentTable" v-for="(item, index) in comments" :key="item.id + '' + index">
                        <tr>
                            <td>
                                <div @mousedown="lookUserMenu(item.userUid, $event)"><el-avatar :size="30"
                                        :src="item.avatar"></el-avatar></div>
                            </td>
                            <td>
                                <span style="font-size: 12px;">{{ item.createdTime }}</span><br>
                                <span style="font-size: 14px;font-weight: 1000;">{{ item.username }}:</span>
                            </td>
                            <td>
                                <div style="float: right;">
                                    <el-button size="mini" class="el-icon-delete" type="danger"
                                        @click="deleteComment(item.id, undefined)"></el-button>
                                    <el-button size="mini" class="el-icon-chat-dot-round" type="info"
                                        @click="isShowSecReply(item.id)"></el-button>
                                </div>

                                <!-- <i class="el-icon-trophy" @click="giveALike(item, item._id)"
                            :class="item.favour.includes(userId) ? 'active' : ''"></i>
                          {{ item.favour.length || 0 }} -->
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td colspan="2">
                                <p>
                                    {{ item.content }}
                                <div class="replyComment" v-show="isShowSec === item.id">
                                    <el-input :placeholder="placeholderText" class="replyCommentInput"
                                        v-model.trim="replyContext" :maxlength="contentLength"
                                        @keyup.enter.native="addComment(item.id, item.userUid, item.id)"></el-input>
                                    <el-button type="primary" size="semlla" class="reply-button el-icon-check"
                                        @click="addComment(item.id, item.userUid, item.id)"></el-button>
                                    <el-button type="info" size="semlla" class="reply-button el-icon-close"
                                        @click="isShowSec = ''"></el-button>
                                </div>
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <td></td>
                            <td colspan="2">
                                <table class="secondComment" v-for="(reply, index) in item.replyInfo"
                                    :key="reply.id + '' + index">
                                    <tr>
                                        <td @mousedown="lookUserMenu(reply.userUid, $event)"><el-avatar :size="25"
                                                :src="reply.avatar"></el-avatar></td>
                                        <td>
                                            <span style="font-size: 10px;">{{ reply.createdTime }}</span><br>
                                            <span style="font-size: 13px;font-weight: 900;">{{ reply.username
                                            }}回复{{ reply.replyName }}</span>
                                        </td>
                                        <td>
                                            <div style="float: right;">
                                                <el-button size="mini" class="el-icon-delete" type="danger"
                                                    @click="deleteComment(reply.id, item.id)"></el-button>
                                                <el-button size="mini" class="el-icon-chat-dot-round" type="info"
                                                    @click="isShowSecReply(reply.id)"></el-button>

                                            </div>


                                            <!-- <i class="el-icon-trophy" @click="giveALike(reply, item._id)"
                                                :class="reply.favour.includes(userId) ? 'active' : ''"></i>
                                            {{ reply.favour ? reply.favour.length : 0 }} -->
                                        </td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td colspan="2">
                                            <p>{{ reply.content }}</p>
                                            <div class="replyComment" v-show="isShowSec === reply.id">
                                                <el-input :placeholder="placeholderText" class="replyCommentInput "
                                                    v-model.trim="replyContext" :maxlength="contentLength"
                                                    @keyup.enter.native="addComment(reply.id, reply.userUid, item.id)"></el-input>
                                                <el-button type="primary" size="mini" class="reply-button el-icon-check"
                                                    style="height: 40px;"
                                                    @click="addComment(reply.id, reply.userUid, item.id)"></el-button>
                                                <el-button type="info" size="mini" style="height: 40px;"
                                                    class="reply-button el-icon-close" @click="isShowSec = ''"></el-button>
                                            </div>
                                        </td>

                                    </tr>
                                </table>
                            </td>

                        </tr>
                    </table>
                    <!-- 暂无评论的空状态 -->
                    <el-empty :description="emptyText" v-show="comments.length === 0"></el-empty>
                </div>
            </el-drawer>
        </div>

    </div>
</template>




<script>
import axios from 'axios';
import { $isLike } from '@/assets/api/user.js'
import { $isCollect } from '@/assets/api/user.js'
import { $commentNumById } from '@/assets/api/user.js'
import { $findArticleById } from '@/assets/api/user.js'
import { $like } from '@/assets/api/user.js'
import { $collect } from '@/assets/api/user.js'
import { $findCommentById } from '@/assets/api/user.js'
import { $deleteComment } from '@/assets/api/user.js'
import { $addComment } from '@/assets/api/user.js'


export default {
    name: 'oneArticle',
    props: {
        articleId: {
            //评论所属文章 id
            type: String
        },
        emptyText: {
            // 评论为空的时候显示的文字
            type: String,
            default: "期待你的评论！"
        },
        buttonText: {
            // 按钮文字
            type: String,
            default: "评论"
        },
        contentLength: {
            // 评论长度
            type: Number,
            default: 150
        },
        placeholderText: {
            // 默认显示文字
            type: String,
            default: "请输入最多150字的评论..."
        }
    },
    data() {
        return {
            commentNum: 0,//文章评论条数
            comments: [], // 获取得到的评论
            context: "", // 评论内容
            replyContext: "", //一级评论回复
            isShowSec: "", //是否显示次级回复框
            isClickId: "", //记录点击回复的评论id
            userId: this.$myContent.userMess.id,
            username: this.$myContent.userMess.nickName,
            userType: this.$myContent.userMess.userType,
            avatar: this.$myContent.userMess.avatar,
            firstIdx: 1,
            secIdx: 1,
            tagList: [],
            tableData: {},//博客列表
            isLike: false,//是否已经点赞
            isCollect: false,//是否已经点赞
            drawer: false,//评论抽屉
            isReNewComment: false,//是否已经自动更新评论
        }
    },
    created() {
        this.initialization();//初始数据查询
    },
    methods: {
        lookUserMenu(uid, event) {
            if (event.button == 0) {
                sessionStorage.setItem("lookUserMessById", uid);
                this.$router.push({
                    name: 'publicBaseMess',
                })
            }
        },

        updateBlog() {

            this.$confirm('是否编辑该文章?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                sessionStorage.setItem("tableData", JSON.stringify(this.tableData));
                sessionStorage.setItem("tagList", JSON.stringify(this.tagList));
                this.$router.push({
                    name: 'updateAtricle'
                })
            }).catch(() => { });
        },

        openComment() {
            this.drawer = true;
            $findCommentById(this.tableData.id).then((res) => {
                if (res.data.success) {
                    this.comments = res.data.data.findCommentById;
                }
            }).catch((err) => {
                console.log(err);
            })
            this.renewComment();//自动更新评论
        },


        //5秒钟自动更新评论
        renewComment() {
            var renew;
            if (!this.isReNewComment) {//需求开启自动更新评论，并且之前没有开启自动评论
                this.isReNewComment = true;
                renew = setInterval(() => {
                    setTimeout(() => {
                        if (this.drawer) {//正在浏览评论，更新评论
                            $findCommentById(this.tableData.id).then((res) => {
                                if (res.data.success) {
                                    this.comments = res.data.data.findCommentById;
                                }
                            }).catch((err) => {
                                console.log(err);
                            })
                        } else {//已经关闭了浏览的评论，关闭该自动更新，并将数据初始化
                            this.isReNewComment = false;//关闭自动更新
                            clearInterval(renew);
                        }
                    }, 0)
                }, 5000)
            } else {

            }

        },


        // 唤起文件选择
        handleClick() {
            this.$refs.avatar.click();
        },
        // 评论点赞
        giveALike(item, _id) {
            try {
                // 不允许同一个人重复点赞
                if (item.favour?.includes(this.userId)) {
                    this.$message.info("您已经点过赞啦！");
                    return;
                }
                //判断是给一级评论点赞还是二级评论，只有二级评论会有replyName
                if (item.replyName) {
                    // 给二级评论点赞，向后台提交数据
                } else {
                    // 一级评论点赞，向后台提交数据
                }
                item.favour.push(this.userId);
            } catch (err) {
                this.$message.error(err);
            }
        },
        isShowSecReply(id) {
            if (id) {
                this.isShowSec = id;
                if (this.isClickId === this.isShowSec) {
                    this.isShowSec = "";
                } else {
                    this.isShowSec = id;
                }
                this.isClickId = this.isShowSec;
            } else {
                this.isShowSec = this.isClickId = "";
            }
        },
        deleteComment(_id, replyId) {
            this.$confirm('是否删除该评论?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                $deleteComment(_id).then((res) => {
                    this.$notify({
                        title: res.data.success ? '删除成功' : '删除失败',
                        type: res.data.success ? 'success' : 'error'
                    })
                    this.openComment();
                }).catch((err) => {
                    console.log(err);
                })
            }).catch(() => {

            });

        },

        async addComment(id, toUserUid, firstComment) {
            let send = {};
            // 评论添加成功，返回的数据
            //本地更新评论列表
            if (toUserUid) {
                // 添加二级评论
                if (!this.replyContext) {
                    this.$message.warning("评论或留言不能为空哦！");
                    return;
                }
                // 模拟数据提交成功后返回数据
                send.data = {
                    userUid: this.userId,//评论的用户id
                    toUid: id,//回复某条评论的评论id
                    articleId: this.articleId, // 评论的文章id
                    content: this.replyContext, //回复内容
                    blogUid: this.tableData.id,//回复某条博客的博客id
                    toUserUid: toUserUid,//回复对象用户的id
                    firstComment: firstComment,//一级评论id
                };

                $addComment(send.data).then((res) => {
                    this.$notify({
                        title: res.data.success ? '评论成功' : '评论失败',
                        type: res.data.success ? 'success' : 'error'
                    });
                    if (res.data.success) {
                        this.openComment();
                        this.replyContext = ''
                    }
                }).catch((err) => {
                    console.log(err);
                })

            } else {
                // 添加一级评论，提交数据到后端
                if (!this.context) {
                    this.$message.warning("评论或留言不能为空哦！");
                    return;
                }
                // 模拟数据提交成功后返回数据
                send.data = {
                    userUid: this.userId,//评论的用户id
                    blogUid: this.tableData.id,//回复某条博客的博客id
                    articleId: this.articleId, // 评论的文章id
                    content: this.context //评论内容
                };
                $addComment(send.data).then((res) => {
                    this.$message({
                        type: res.data.success ? "success" : "error",
                    })
                    if (res.data.success) {
                        this.openComment();
                        this.context = ''
                    }
                }).catch((err) => {
                    console.log(err);
                })


            }
            this.isShowSec = this.isClickId = "";
        },

        async initialization() {
            //获取文章id
            this.tableData.id = JSON.parse(sessionStorage.getItem("blogId"));
            await $findArticleById(this.tableData.id, this.userId).then((res) => {
                if (res.data.success) {
                    this.tableData = res.data.data.wqunBlog;
                    this.tagList = res.data.data.tagAr;
                } else {
                    this.message(res)
                }
            }).catch((err) => {
                console.log(err);
            })

            //判断是否点赞该文章
            this.userId = this.$myContent.userMess.id;
            this.username = this.$myContent.userMess.nickName;
            this.userType = this.$myContent.userMess.userType;
            this.avatar = this.$myContent.userMess.avatar;
            await $isLike({ id: this.userId, blogId: this.tableData.id }).then((res) => {
                if (res.data.success) {
                    this.isLike = true;
                } else {
                    this.isLike = false;
                }
            }).catch((err) => {
                console.log(err);
            })

            //判断是否收藏该文章
            await $isCollect({ id: this.userId, blogId: this.tableData.id }).then((res) => {
                if (res.data.success) {
                    this.isCollect = true;
                } else {
                    this.isCollect = false;
                }
            }).catch((err) => {
                console.log(err);
            })


            //评论数量
            await $commentNumById(this.tableData.id).then((res) => {
                if (res.data.success) {
                    this.commentNum = res.data.data.commentNumById;
                }
            }).catch((err) => {
                console.log(err);
            })
        },

        //点赞
        like() {
            $like({ id: this.userId, blogId: this.tableData.id }).then((res) => {
                if (res.data.success) {
                    this.tableData.likeCount = res.data.data.likeCount;
                    this.isLike = !this.isLike;
                } else {
                    this.message(res);
                }
            }).catch((err) => {
                console.log(err);
            })

        },


        //收藏
        collect() {
            $collect({ id: this.userId, blogId: this.tableData.id }).then((res) => {
                if (res.data.success) {
                    this.tableData.collectCount = res.data.data.collectCount;
                    this.isCollect = !this.isCollect;
                } else {
                    this.message(res);
                }
            }).catch((err) => {
                console.log(err);
            })
        },
    }
}
</script>

<style>
.item {
    margin-bottom: 60px;
}

.contentDiv img {
    max-width: 800px;
}
</style>


<style scoped>
.blog {
    padding-right: 20px;
    height: 600px;
    width: 900px;
    overflow-y: scroll;
}

.contentDiv {}

.drawer {
    width: 600px;
}

.secondComment {
    width: 100%;
}

.commentTable {
    width: 90%;
    margin: 0 auto;

}

.replyComment {
    width: 100%;
}

.replyCommentInput {
    width: 70%;
    height: 10px;
}

.commentTable td:nth-child(1) {
    width: 6%;
}

.commentTable td:nth-child(2) {}

.commentTable td:nth-child(3) {
    width: 40%;
}

.left {
    padding: 10px;
}


.comment {
    min-height: 26vh;
    border-radius: 5px;
    margin-top: 2px;
    overflow: hidden;

    .comment-header {
        position: relative;
        height: 50px;
        padding: 10px 5px;
        display: flex;
        align-items: center;

        .input {
            margin-left: 10px;
            margin-right: 20px;
            flex: 1;
        }
    }
}

.rigth {
    background-color: #cccccc;
    min-width: 100px;
    height: 1000px;
    padding: 10px;
    margin: 2%;
    margin-left: 12%;
}



.contianer {
    min-width: 1220px;
}



.articleFooter {
    position: absolute;
    top: 230px;
    width: 30px;
    margin-left: -140px;
}

.like {

    background-image: url("../../../assets/images/blogAdmin/like.svg");
    background-size: 30px;
    background-repeat: no-repeat;
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-left: 50px;
}

.noLike {

    background-image: url("../../../assets/images/blogAdmin/noLike.svg");
    background-size: 30px;
    background-repeat: no-repeat;
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-left: 50px;


}

.collect {

    background-image: url("../../../assets/images/blogAdmin/collect.svg");
    background-size: 30px;
    background-repeat: no-repeat;
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-left: 50px;
}

.noCollect {

    background-image: url("../../../assets/images/blogAdmin/noCollect.svg");
    background-size: 30px;
    background-repeat: no-repeat;
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-left: 50px;
}

.commentbtn {
    background-image: url("../../../assets/images/blogAdmin/comment.svg");
    background-size: 30px;
    background-repeat: no-repeat;
    width: 30px;
    height: 30px;
    display: inline-block;
    margin-left: 50px;
}

i {
    padding: 10px;
    margin-left: 2%;
}

h1 {
    font-size: 29px;
    text-align: center;
}
</style>

<style>
* {
    font-family: "Hiragino Sans GB"
}


.el-row {
    margin-bottom: 20px;

    &:last-child {
        margin-bottom: 0;
    }
}

.el-col {
    border-radius: 4px;
}

.bg-purple-dark {
    background: #99a9bf;
}

.bg-purple {
    background: white;
    padding-top: 20px;
    min-width: 850px;
    margin-left: 13%;
}

.PSrticletag {}

.bg-purple-light {
    background: #e5e9f2;
}





.bg-purple-darkRigth {
    background: #99a9bf;

}

.bg-purpleRigth {
    background: white;
    padding: 50px;

}

.bg-purple-lightRigth {
    background: #e5e9f2;
}

.grid-contentRigth {
    border-radius: 4px;
    min-height: 36px;
}



.row-bg {
    padding: 10px;
    background-color: #f9fafc;
}
</style>
